/* 
Scenic Graphics Library
Copyright (C) 2007 Jouni Tulkki

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USApackage scenic;
*/

package scenic.toolkit.db;

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;

import scenic.toolkit.db.event.ChangeEvent;

public abstract class Node implements NodeListener {
	private LinkedList<WeakReference<NodeListener>> listeners = 
		new LinkedList<WeakReference<NodeListener>>();
	
	public Type getType() {
		return null;
	}
	
	public abstract void storeTo(StorageOutputStream stream);
	
	protected void notifyChange(ChangeEvent event) {
		changed(event);
	}
	
	public void changed(ChangeEvent event) {
		for(WeakReference<NodeListener> o : listeners)
			o.get().changed(event);
	}
	
	protected void addListener(NodeListener listener) {
		listeners.add(new WeakReference<NodeListener>(listener));
	}
	
	protected void removeListener(NodeListener listener) {
		Iterator<WeakReference<NodeListener>> itr = listeners.iterator();
		
		while(itr.hasNext())
		{
			WeakReference<NodeListener> ref = itr.next();
			
			if(ref.get() == listener)
			{
				itr.remove();
				break;
			}			
		}
	}
	
	protected void addLink(Node node) {
		if(node != null)
			node.addListener(this);
	}
	
	protected void removeLink(Node node) {
		if(node != null)
			node.removeListener(this);
	}	
}
